package com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.BizOrderResponse;
import com.yxhl.protobuf.OrderRideStatus;
import com.yxhl.protobuf.ServiceType;
import com.yxhl.protobuf.StationEntry;
import com.yxhl.protobuf.TcpResponse;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.core.func.map.overlay.DrivingRouteOverlay;
import com.yxhl.zoume.core.func.map.ui.fragment.BaseMapFragment;
import com.yxhl.zoume.core.func.tcp.TcpRequestProvider;
import com.yxhl.zoume.core.tripsmgmt.ui.CustomDrivingRouteOverlay;
import com.yxhl.zoume.core.tripsmgmt.ui.activity.BusMapContainerActivity;
import com.yxhl.zoume.data.tcp.OnChannelListener;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.ZMMapUtils;
import com.yxhl.zoume.utils.tcp.TcpService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by sugarya
 */
public class ZouMeBusStationPositionFragment extends BaseMapFragment implements RouteSearch.OnRouteSearchListener, AMap.InfoWindowAdapter, AMap.OnMarkerClickListener, ServiceConnection {

    private static final int SUCCESS = 1000;
    private static final String TAG = "PositionMap";
    private static final float MAP_ZOOM_LEVEL = 13f;
    private static final int TCP_REQUEST_PERIOD = 10 * 1000;

    //widgets
    @BindView(R.id.frame_custom_bus_station_location)
    FrameLayout stationLocationFrame;

    //arguments
    private RouteSearch mRouteSearch;

    private LatLonPoint mStartPoint;
    private LatLonPoint mTargetPoint;

    /**
     * 途径点集合
     */
    private List<LatLonPoint> mArrivalPointList;

    /**
     * 途径点Marker打点
     */
    private ArrayList<Marker> mArrivalMarkerList;
    private ArrayList<MarkerOptions> mArrivalMarkerOptionList;

    //行程订单编号
    private String mOrderSerial;

    private TcpService.TcpClientController mTcpClientController;
    private BizOrderResponse mBizOrderResponse;

    /**
     * 是否是上车站点标志位
     */
    private int mIsGetIndex = -1;

    private boolean mFirstRun = true;

    //上一个位置定位图标
    private Marker mLastLocationMarker;
    //上一个位置的巴士图标
    private Marker mLastBusMarker;
    //上一个位置接驳车图标
    private Marker mLastShuttleMarker;
    private DrivingRouteOverlay mDrivingRouteOverlay;


    public ZouMeBusStationPositionFragment() {

    }

    public static ZouMeBusStationPositionFragment newInstance(BizOrderResponse bizOrderResponse) {
        Bundle args = new Bundle();
        args.putSerializable(UIConstants.TripContainer.ARGUMENT_KEY_ZOU_ME_POSITION_MAP_BIZ_ORDER, bizOrderResponse);
        ZouMeBusStationPositionFragment fragment = new ZouMeBusStationPositionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化成员变量
        initializeField();
        handlerArgument();
        onRxBusEvent();
        bindTcpService();
    }

    private void handlerArgument() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mBizOrderResponse = (BizOrderResponse) arguments.getSerializable(UIConstants.TripContainer.ARGUMENT_KEY_ZOU_ME_POSITION_MAP_BIZ_ORDER);
            if (mBizOrderResponse != null) {
                mOrderSerial = getOrderSerial();
                initArrivalPointLatLng();
            }
        }
    }

    /**
     * 获取订单编号
     *
     * @return
     */
    private String getOrderSerial() {
        List<BizOrder> bizOrderList = mBizOrderResponse.getOrderFieldsesList();
        if (bizOrderList != null && bizOrderList.size() > 0) {
            BizOrder bizOrder = bizOrderList.get(0);
            if (bizOrder != null) {
                return bizOrder.getOrderSerial();
            }
        }
        return "";
    }

    private void onRxBusEvent() {

//        getSubscription().add(toSubscription(TcpChannelActiveEvent.class, new Action1<TcpChannelActiveEvent>() {
//            @Override
//            public void call(TcpChannelActiveEvent tcpChannelActiveEvent) {
//                LOG.e(TAG,"tcpChannelActiveEvent");
//                mTcpClientController.sendTcpRequest(
//                        TcpRequestProvider.newInstance().init(mActivity, mOrderSerial)
//                                .getTcpRequest(ServiceType.USER_QUERY_LOC));
//            }
//        }));

//        getSubscription().add(toSubscription(TcpLocationRenderEvent.class, new Action1<TcpLocationRenderEvent>() {
//            @Override
//            public void call(TcpLocationRenderEvent tcpLocationRenderEvent) {
//                LOG.e(TAG,"TcpLocationRenderEvent");
//                if (tcpLocationRenderEvent != null) {
//                    TcpResponse tcpResponse = tcpLocationRenderEvent.getResponse();
//                    if (tcpResponse != null) {
//                        boolean isSucc = tcpResponse.getIsSucc();
//                        if (isSucc) {
//                            LOG.e(TAG, "TcpLocationRenderEvent RefreshMap");
//                            showTest("TcpLocationRenderEvent RefreshMap");
//                            BizOrderResponse bizOrderResp = tcpResponse.getBizOrderResp();
//                            RefreshMap(bizOrderResp);
//                        }
//                    }
//                }
//            }
//        }));
    }

    /**
     * 刷新地图
     *
     * @param bizOrderResp
     */
    private void RefreshMap(BizOrderResponse bizOrderResp) {
        LOG.e(TAG, "RefreshMap");
        if (bizOrderResp != null) {
            LOG.e(TAG, "RefreshMap clear");
            LatLonPoint shuttlePoint = null;
            LatLonPoint busPoint = null;
            List<com.yxhl.protobuf.Location> locationList = bizOrderResp.getLnglatsList();

            for (com.yxhl.protobuf.Location location : locationList) {
                String locType = location.getLocType();
                String latStr = location.getLat();
                String lngStr = location.getLng();
                LOG.e(TAG, "locType=" + locType);
                switch (locType) {
                    case "car":
                        try {
                            shuttlePoint = new LatLonPoint(Double.parseDouble(latStr), Double.parseDouble(lngStr));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case "bus":
                        try {
                            busPoint = new LatLonPoint(Double.parseDouble(latStr), Double.parseDouble(lngStr));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }

            if (shuttlePoint != null) {
                initializeShuttleDriverMarker(shuttlePoint);
            }
            if (busPoint != null) {
                initializeBusDriverMarker(busPoint);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initializeMapListener();

        initializeArrivalMarker();
        startDrivingRouteSearch();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        startLocation();
    }

    @OnClick(R.id.frame_custom_bus_station_location)
    public void onStationLocationClick(View view) {
        LatLng latLng = null;
        if (mLastLocationMarker != null) {
            latLng = mLastLocationMarker.getPosition();
        } else {
            if (mLastBusMarker != null) {
                latLng = mLastBusMarker.getPosition();
            }
        }
        if (latLng != null) {
            animateMoveTo(new LatLng(latLng.latitude, latLng.longitude), MAP_ZOOM_LEVEL);
        }
    }


    private void initializeField() {
        mArrivalPointList = new LinkedList<>();
        mArrivalMarkerOptionList = new ArrayList<>();

    }

    private void initializeMapListener() {
        mMapView.getMap().setInfoWindowAdapter(this);
        mMapView.getMap().setOnMarkerClickListener(this);
    }

    private void startDrivingRouteSearch() {
        mRouteSearch = new RouteSearch(mActivity);
        mRouteSearch.setRouteSearchListener(this);

        RouteSearch.DriveRouteQuery driveRouteQuery = new RouteSearch.DriveRouteQuery(
                new RouteSearch.FromAndTo(mStartPoint, mTargetPoint),
                RouteSearch.DrivingDefault,
                mArrivalPointList,
                null,
                "");
        mRouteSearch.calculateDriveRouteAsyn(driveRouteQuery);
    }

    /**
     * 途径站点经纬度
     */
    private void initArrivalPointLatLng() {
        List<StationEntry> stationEntryList = mBizOrderResponse.getStationsList();
        int size = stationEntryList.size();
        for (int i = 0; i < size; i++) {
            StationEntry stationEntry = stationEntryList.get(i);
            String latitude = stationEntry.getLatitude();
            String longitude = stationEntry.getLongitude();
            LatLonPoint latLonPoint = new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
            mArrivalPointList.add(latLonPoint);

            if (i == 0) {
                mStartPoint = latLonPoint;
            } else if (i == size - 1) {
                mTargetPoint = latLonPoint;
            }
        }
    }

    /**
     * 途径站点Marker
     */
    private void initializeArrivalMarker() {
        if (mBizOrderResponse != null) {
            List<StationEntry> stationEntryList = mBizOrderResponse.getStationsList();
            int size = stationEntryList.size();
            for (int i = 0; i < size; i++) {
                StationEntry stationEntry = stationEntryList.get(i);
                String latitude = stationEntry.getLatitude();
                String longitude = stationEntry.getLongitude();
                LatLonPoint latLonPoint = new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions
                        .title("")
                        .anchor(0.5f, 0.5f)
                        .setInfoWindowOffset(0, 5)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_meiyoujinguozhandian))
                        .position(ZMMapUtils.convertToLatLng(latLonPoint));
                mArrivalMarkerOptionList.add(markerOptions);

                boolean isGet = stationEntry.getIsGet();
                LOG.e(TAG, "isGet=" + isGet + "  when index =" + i);
                if (isGet) {
                    mIsGetIndex = i;
                }
            }
            mArrivalMarkerList = mMapView.getMap().addMarkers(mArrivalMarkerOptionList, true);

            if (mIsGetIndex >= 0 && mIsGetIndex < mArrivalMarkerList.size()) {
                mArrivalMarkerList.get(mIsGetIndex).showInfoWindow();
            }
        }
    }


    /**
     * 接驳车位置
     */
    private void initializeShuttleDriverMarker(LatLonPoint shuttleDriverPoint) {

        MarkerOptions driverMarkerOptions = new MarkerOptions();
        driverMarkerOptions
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_jieche))
                .position(ZMMapUtils.convertToLatLng(shuttleDriverPoint));

        if (mLastShuttleMarker != null) {
            mLastShuttleMarker.remove();
        }
        mLastShuttleMarker = mMapView.getMap().addMarker(driverMarkerOptions);
    }

    /**
     * 巴士位置
     */
    private void initializeBusDriverMarker(LatLonPoint busDriverPoint) {
        MarkerOptions driverMarkerOptions = new MarkerOptions();
        driverMarkerOptions
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_bs))
                .position(ZMMapUtils.convertToLatLng(busDriverPoint));

        if (mLastBusMarker != null) {
            mLastBusMarker.remove();
        }
        mLastBusMarker = mMapView.getMap().addMarker(driverMarkerOptions);
    }


    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int code) {
        if (code == SUCCESS) {
            if (driveRouteResult != null) {
                List<DrivePath> drivePathList = driveRouteResult.getPaths();
                if (drivePathList != null && drivePathList.size() > 0) {
                    DrivePath drivePath = drivePathList.get(0);
                    mDrivingRouteOverlay = new CustomDrivingRouteOverlay(
                            mActivity,
                            mMapView.getMap(),
                            drivePath,
                            driveRouteResult.getStartPos(),
                            driveRouteResult.getTargetPos(),
                            mStartPoint,
                            mTargetPoint
                    );
                    mDrivingRouteOverlay.setThroughPointIconVisibility(false);
                    mDrivingRouteOverlay.setNodeIconVisibility(false);
                    mDrivingRouteOverlay.removeFromMap();
                    mDrivingRouteOverlay.addToMap();
                    mDrivingRouteOverlay.zoomToSpan();

                    //移动到定位处的标示
                    mBaseStartMoveToLocation = true;
                }
            }
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        return false;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        List<StationEntry> stationEntryList = mBizOrderResponse.getStationsList();
        int stationListSize = stationEntryList.size();
        for (int i = 0; i < stationListSize; i++) {
            if (marker.equals(mArrivalMarkerList.get(i))) {
                View infoWindow = LayoutInflater.from(mActivity).inflate(R.layout.station_info_window, null);
                TextView stationNameTv = (TextView) infoWindow.findViewById(R.id.custom_bus_station_name);
                TextView stationTimeTv = (TextView) infoWindow.findViewById(R.id.custom_bus_station_time);

                StationEntry stationEntry = stationEntryList.get(i);
                String stationName = stationEntry.getStationName();
                String arrivalTime = stationEntry.getTime();

                if (!TextUtils.isEmpty(stationName)) {
                    stationNameTv.setText(stationName);
                } else {
                    stationNameTv.setText("");
                }

                if (!TextUtils.isEmpty(arrivalTime)) {
                    stationTimeTv.setText(arrivalTime);
                } else {
                    stationTimeTv.setText("");
                }

                return infoWindow;
            }
        }

        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mTcpClientController = (TcpService.TcpClientController) service;

        mTcpClientController.startTcpConnection(new OnChannelListener() {

            private Timer timer;

            @Override
            public void onChannelActive() {
                LOG.e(TAG, "onChannelActive");
            }

            @Override
            public void onConnectionSuccess() {
                LOG.e(TAG, "onConnectionSuccess");
                if (timer != null) {
                    timer.cancel();
                }
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(mOrderSerial)) {
                            mTcpClientController.sendTcpRequest(
                                    TcpRequestProvider.getInstance().init(getContext(), mOrderSerial)
                                            .getTcpRequest(ServiceType.USER_QUERY_LOC));
                        }
                    }
                }, 0, TCP_REQUEST_PERIOD);
            }

            @Override
            public void onChannelInactive() {
                LOG.e(TAG, "onChannelInactive");
                if (timer != null) {
                    timer.cancel();
                }
            }

            @Override
            public void onChannelRead(TcpResponse tcpResponse) {
                LOG.e(TAG, "onChannelRead");
                if (tcpResponse != null) {
                    boolean isSucc = tcpResponse.getIsSucc();
                    if (isSucc) {
                        LOG.e(TAG, "isSucc onChannelRead");
                        BizOrderResponse bizOrderResp = tcpResponse.getBizOrderResp();
                        RefreshMap(bizOrderResp);
                    }
                }
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }


    private void bindTcpService() {
        Intent intent = new Intent(mActivity, TcpService.class);
        mActivity.bindService(intent, this, Context.BIND_AUTO_CREATE);
    }

    private void unbindTcpService() {
        mActivity.unbindService(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindTcpService();
    }


    @Override
    protected Marker getLocationMarker(AMap aMap, LatLng latLng) {
        LOG.e(TAG, "getLocationMarker");

        //当乘客上车后,自身定位图标取消,只显示巴士或接驳车的定位
        if (mBizOrderResponse != null) {
            BizOrder bizOrder = mBizOrderResponse.getOrderFieldses(0);
            if (bizOrder != null) {
                OrderRideStatus rideStatus = bizOrder.getRideStatus();
                switch (rideStatus) {
                    case UN_SEND://未派车
                        break;
                    case UN_TAKEN://未上车
                        break;
                    case PART_TAKEN: //部分上车
                    case TAKEN://已上车
                        return null;
                    case ARRIVED://已到站
                    case PART_ARRIVED: //部分已到站
                        break;
                    case RIDE_INVALID://未乘坐
                    case DROP: //已放弃
                        break;
                    default:
                }
            }
        }

        MarkerOptions markerOptions = new MarkerOptions();
        Bitmap iconBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_wo);
        markerOptions
                .anchor(0.5f, 0.5f)
                .setFlat(true)
                .icon(BitmapDescriptorFactory.fromBitmap(iconBmp))
                .position(latLng);


        if (mLastLocationMarker != null) {
            mLastLocationMarker.remove();
        }
        mLastLocationMarker = aMap.addMarker(markerOptions);

        return mLastLocationMarker;
    }

    @Override
    protected boolean setUpLocationStyle(AMap aMap) {
        // 设置定位类型

//        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_wo));
//        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
//        myLocationStyle.strokeColor(Color.TRANSPARENT);
//        aMap.setMyLocationStyle(myLocationStyle);
        return false;
    }

    @Override
    protected float getLocationMapZoomLevel() {
        return MAP_ZOOM_LEVEL;
    }

    @Override
    protected void secondAnimateMove() {

    }


    @Override
    protected void initializeInjector() {
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_custom_bus_station_position;
    }

    @Override
    protected void setupToolBar() {
        ((BusMapContainerActivity) mActivity).setToolbarTitle("位置信息");
    }

}
